package com.yy.tools.signtools;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.kit.HashKit;
import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfigKit;


public class JsApi {
    private final static String access_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=TOKEN&type=jsapi";
    // 利用 appId 与 accessToken 建立关联，支持多账户
    private static Map<String, JsapiTicket> ticketMap = new ConcurrentHashMap<String, JsapiTicket>();
 
    /**
     * 获取jsapi_ticket
     * 
     * @param access_token
     * @return
     */
    public static JsapiTicket getJsapiTicket() {
 
        String appId = ApiConfigKit.getApiConfig().getAppId();
        JsapiTicket result = ticketMap.get(appId);
        if (result != null && result.isAvailable())
            return result;
 
        refreshTicket();
 
        return ticketMap.get(appId);
    }
 
    /**
     * 强制更新 ticket
     */
    public static synchronized void refreshTicket() {
        String appId = ApiConfigKit.getApiConfig().getAppId();
        JsapiTicket ticket = null;
 
        for (int i = 0; i < 3; i++) { // 最多三次请求
            String token = AccessTokenApi.getAccessToken().getAccessToken();
            String requestUrl = access_ticket_url.replace("TOKEN", token);
            String json = HttpKit.get(requestUrl);
            ticket = new JsapiTicket(json);
 
            if (ticket.isAvailable())
                break;
        }
 
        // 三次请求如果仍然返回了不可用的JsapiTicket 仍然 put 进去，便于上层通过 JsapiTicket 中的属性判断底层的情况
        ticketMap.put(appId, ticket);
    }
 
    /**
     * 获取jsApi签名
     */
    public static String getWxSingature(long timestamp, String nonceStr,
            String url) {
 
        String singature = null;
        JsapiTicket ticket = getJsapiTicket();
        if (ticket.isAvailable()) {
            String ticketStr = ticket.getTicket();
            String str = "jsapi_ticket=" + ticketStr + "&noncestr=" + nonceStr
                    + "&timestamp=" + timestamp + "&url=" + url;
            singature = HashKit.sha1(str);
        }
 
        return singature;
 
    }
}